import { createRouter, createWebHistory, type RouteRecordRaw } from "vue-router";
import { BASE_URL } from '@/config/configuration'
import type { RouterMeta } from "@/types/routerMeta";

const modules = import.meta.glob("@/views/**/meta.ts", {
  eager: true,
  import: "meta",
});
const vueModules = import.meta.glob("@/views/**/index.vue", { eager: false });
const layoutModule = import.meta.glob("@/layout/index.vue", { eager: false });

const moduleRouter: Array<RouteRecordRaw> = Object.entries(modules).map(([pagePath, config]) => {
  const path = pagePath.replace('/src/views', '').replace('/meta.ts', '');
  const name = path.substring(path.lastIndexOf('/') + 1)
  const pathComponent = pagePath.replace('meta.ts', 'index.vue');

  const vueComponent = vueModules[pathComponent];
  const metaInfo: RouterMeta= config as RouterMeta;

  return {
    path: path,
    name: name,
    redirect: path + '/index',
    component: layoutModule['/src/layout/index.vue'],
    children: [
      {
        path: 'index',
        name: name + 'Index',
        component: vueComponent,
        meta: {
          title: metaInfo.title,
          icon: metaInfo.icon,
          sort: metaInfo.sort
        }
      }
    ],
  };
}).filter(Boolean);
export const asyncRouter = [...moduleRouter];

const rootRouter: RouteRecordRaw = {
  path: '/',
  name: 'Layout',
  component: layoutModule['/src/layout/index.vue'](),
  redirect: BASE_URL,
  children: []
}

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [rootRouter, ...moduleRouter]
});

export default router;
